package com.origin.baselibrary.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.origin.baselibrary.R
import com.origin.baselibrary.activity.style.ImmersiveActivity
import com.origin.baselibrary.databinding.ActivityInstallAppBinding
import com.origin.baselibrary.utils.AppFileUtils
import com.origin.utils.log.LogUtils
import java.io.File

class InstallAppActivity : ImmersiveActivity<ActivityInstallAppBinding>(R.layout.activity_install_app) {
    companion object {
        fun launcher(activity: Activity, appFilePath: String) {
            val intent = Intent(activity, InstallAppActivity::class.java)
            intent.putExtra("appFilePath", appFilePath)
            activity.startActivity(intent)
        }
    }

    private final val INSTALL_PERMISS_CODE = 10001


    lateinit var appFilePath: String;
    override fun initContentView() {
        appFilePath = intent.getStringExtra("appFilePath") ?: ""
        if (TextUtils.isEmpty(appFilePath)) {
            finish()
            return
        }
        //兼容8.0
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            // 判断是否有权限
//            val haveInstallPermission = mContext.packageManager.canRequestPackageInstalls()
//            if (!haveInstallPermission) {
//                //权限没有打开则提示用户去手动打开
//                // 开启当前应用的权限管理页
//
//                // 开启当前应用的权限管理页
//                val packageUri: Uri = Uri.parse("package:" + this@InstallAppActivity.getPackageName())
//                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri)
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                startActivityForResult(intent, INSTALL_PERMISS_CODE);
//                return
//            }
//        }
        AppFileUtils.installApk(File(appFilePath), this.application)
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtils.__e("onActivityResult  resultCode $requestCode  resultCode  $resultCode")
        if (resultCode == RESULT_OK && requestCode == INSTALL_PERMISS_CODE) {
            AppFileUtils.installApk(File(appFilePath), this@InstallAppActivity.application)
        }
        finish()
    }

    override fun pageLogical() {
    }
}